package com.aipartner.controller;

import com.aipartner.common.PageResult;
import com.aipartner.common.Result;
import com.aipartner.entity.UserTask;
import com.aipartner.entity.WalletTransaction;
import com.aipartner.service.PersonalService;
import com.aipartner.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;

/**
 * Personal Center Controller
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@RestController
@RequestMapping("/api/personal")
@RequiredArgsConstructor
@Validated
@Slf4j
@Api(tags = "Personal Center")
public class PersonalController {
    
    private final PersonalService personalService;
    
    /**
     * Get user statistics
     */
    @GetMapping("/stats")
    @ApiOperation("Get User Statistics")
    public Result<Map<String, Object>> getUserStats() {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            Map<String, Object> stats = personalService.getUserStats(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("Error getting user stats", e);
            return Result.fail("Failed to get user statistics");
        }
    }
    
    /**
     * Get user favorites
     */
    @GetMapping("/favorites")
    @ApiOperation("Get User Favorites")
    public PageResult<Map<String, Object>> getUserFavorites(
            @ApiParam("Content type filter") @RequestParam(required = false) String type,
            @ApiParam("Current page") @RequestParam(defaultValue = "1") @Min(1) Long current,
            @ApiParam("Page size") @RequestParam(defaultValue = "10") @Min(1) Long size) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return new PageResult<>(401, "User not logged in", new ArrayList<>(), 
                                       0L, 0L, true, true, 
                                       current.intValue(), size.intValue());
            }
            
            PageResult<Map<String, Object>> favorites = personalService.getUserFavorites(userId, type, current, size);
            return favorites;
        } catch (Exception e) {
            log.error("Error getting user favorites", e);
            return new PageResult<>(500, "Failed to get favorites", new ArrayList<>(), 
                                   0L, 0L, true, true, 
                                   current.intValue(), size.intValue());
        }
    }
    
    /**
     * Add to favorites
     */
    @PostMapping("/favorites")
    @ApiOperation("Add to Favorites")
    public Result<String> addToFavorites(@RequestBody Map<String, Object> request) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            // 从请求体中提取参数
            String type = (String) request.get("type");
            String contentId = (String) request.get("contentId");
            String title = (String) request.get("title");
            String content = (String) request.get("content");
            String imageUrl = (String) request.get("imageUrl");
            String contentData = (String) request.get("contentData");
            
            // 验证必需参数
            if (type == null || type.trim().isEmpty()) {
                return Result.fail("Content type is required");
            }
            if (contentId == null || contentId.trim().isEmpty()) {
                return Result.fail("Content ID is required");
            }
            if (title == null || title.trim().isEmpty()) {
                return Result.fail("Title is required");
            }
            
            boolean success = personalService.addToFavorites(userId, type, contentId, title, content, imageUrl, contentData);
            return success ? Result.success("Added to favorites successfully") 
                          : Result.fail("Failed to add to favorites");
        } catch (Exception e) {
            log.error("Error adding to favorites", e);
            return Result.fail("Failed to add to favorites");
        }
    }
    
    /**
     * Remove from favorites by favorite ID
     */
    @DeleteMapping("/favorites/{favoriteId}")
    @ApiOperation("Remove from Favorites by ID")
    public Result<String> removeFromFavorites(@PathVariable Long favoriteId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            boolean success = personalService.removeFromFavorites(userId, favoriteId);
            return success ? Result.success("Removed from favorites successfully") 
                          : Result.fail("Failed to remove from favorites");
        } catch (Exception e) {
            log.error("Error removing from favorites", e);
            return Result.fail("Failed to remove from favorites");
        }
    }
    
    /**
     * Remove from favorites by content
     */
    @DeleteMapping("/favorites/content/{contentType}/{contentId}")
    @ApiOperation("Remove from Favorites by Content")
    public Result<String> removeFromFavoritesByContent(
            @PathVariable String contentType,
            @PathVariable String contentId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            boolean success = personalService.removeFromFavoritesByContent(userId, contentType, contentId);
            return success ? Result.success("Removed from favorites successfully") 
                          : Result.fail("Failed to remove from favorites");
        } catch (Exception e) {
            log.error("Error removing from favorites by content", e);
            return Result.fail("Failed to remove from favorites");
        }
    }
    
    /**
     * Get user tasks
     */
    @GetMapping("/tasks")
    @ApiOperation("Get User Tasks")
    public Result<PageResult<UserTask>> getUserTasks(
            @ApiParam("Task status") @RequestParam(required = false) Integer status,
            @ApiParam("Current page") @RequestParam(defaultValue = "1") @Min(1) Long current,
            @ApiParam("Page size") @RequestParam(defaultValue = "10") @Min(1) Long size) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            PageResult<UserTask> tasks = personalService.getUserTasks(userId, status, current, size);
            return Result.success(tasks);
        } catch (Exception e) {
            log.error("Error getting user tasks", e);
            return Result.fail("Failed to get tasks");
        }
    }
    
    /**
     * Complete user task
     */
    @PostMapping("/tasks/{taskId}/complete")
    @ApiOperation("Complete User Task")
    public Result<String> completeUserTask(@PathVariable Long taskId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            boolean success = personalService.completeUserTask(userId, taskId);
            return success ? Result.success("Task completed successfully") 
                          : Result.fail("Failed to complete task");
        } catch (Exception e) {
            log.error("Error completing user task", e);
            return Result.fail("Failed to complete task");
        }
    }
    
    /**
     * Get wallet balance
     */
    @GetMapping("/wallet/balance")
    @ApiOperation("Get Wallet Balance")
    public Result<BigDecimal> getWalletBalance() {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            BigDecimal balance = personalService.getWalletBalance(userId);
            return Result.success(balance);
        } catch (Exception e) {
            log.error("Error getting wallet balance", e);
            return Result.fail("Failed to get wallet balance");
        }
    }
    
    /**
     * Get wallet transactions
     */
    @GetMapping("/wallet/transactions")
    @ApiOperation("Get Wallet Transactions")
    public Result<PageResult<WalletTransaction>> getWalletTransactions(
            @ApiParam("Current page") @RequestParam(defaultValue = "1") @Min(1) Long current,
            @ApiParam("Page size") @RequestParam(defaultValue = "10") @Min(1) Long size) {
        try {
            Long userId = UserContext.getCurrentUserId();
            if (userId == null) {
                return Result.fail("User not logged in");
            }
            
            PageResult<WalletTransaction> transactions = personalService.getWalletTransactions(userId, current, size);
            return Result.success(transactions);
        } catch (Exception e) {
            log.error("Error getting wallet transactions", e);
            return Result.fail("Failed to get wallet transactions");
        }
    }
}